<?php

namespace app\api\controller;


use app\common\controller\Api;
use think\facade\Log;
use app\admin\model\Record as RecordModel;


/**
 * 通知回调
 */
class Esign extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    /**
     * 回调
     * @return void
     */
    public function notify()
    {

        $file = fopen('callback.log', "a");
        try {


            $esign = new  \third\Esign();
            $config = $esign->config;
            $secret = $config['eSignAppSecret']; //项目对应密钥

            //    此处可以打印下日志

            fwrite($file, "startTime\n" . date('Y-m-d H:i:s'));

            file_get_contents("php://input");

            if ($_SERVER['REQUEST_METHOD'] != 'POST') {
                fwrite($file, '非法回调');
                exit;
            }
            fwrite($file, json_encode($_SERVER));

            //    校验签名 如果header里放入的值为X_TSIGN_OPEN_SIGNATURE，到header里会自动加上HTTP_，并且转化为大写，取值时如下
            if (!isset($_SERVER['HTTP_X_TSIGN_OPEN_SIGNATURE'])) {
                echo "签名不能为空\n";
                exit;
            }
            $sign = $_SERVER['HTTP_X_TSIGN_OPEN_SIGNATURE'];
            fwrite($file, 'sign:' . $sign);


            //1.获取时间戳的字节流
            if (!isset($_SERVER['HTTP_X_TSIGN_OPEN_TIMESTAMP'])) {
                echo "时间戳不能为空\n";
                exit;
            }
            $timeStamp = $_SERVER['HTTP_X_TSIGN_OPEN_TIMESTAMP'];

            //2.获取query请求的字节流，对 Query 参数按照字典对 Key 进行排序后,按照value1+value2方法拼接
            $params = $_GET;
            if (!empty($params)) {
                ksort($params);
            }

            $requestQuery = '';
            foreach ($params as $val) {
                $requestQuery .= $val;
            }
            fwrite($file, '获取query的数据:' . $requestQuery . "\n");

            //3. 获取body的数据
            $body = file_get_contents("php://input");
            fwrite($file, '获取body的数据:' . $body . "\n");

            //4.组装数据并计算签名
            $data = $timeStamp . $requestQuery . $body;
            fwrite($file, '组装数据并计算签名:' . $data . "\n");
            $mySign = hash_hmac("sha256", $data, $secret);
            if ($mySign != $sign) {
                echo '验签失败';
                fwrite($file, "签名校验失败\n");
            } else {
                echo '验签成功';
            }

            $result = json_decode($body, true);
            $RecordModel = new RecordModel();
            switch ($result['action']) {
                case 'OPERATOR_READ':
                    //签署人已读通知
                    $signFlowId = $result['signFlowId'];
                    $accountMobile = $result['operator']['psnAccount']['accountMobile'];
                    $record = $RecordModel->where('flowId', $signFlowId)->find();
                    if (empty($record)) {
                        echo '信息异常';
                    }
                    if ($accountMobile == $record['mobile1']) {
                        $RecordModel->where('flowId', $signFlowId)->update(['user1_sign_status' => 1]);
                    }
                    if ($accountMobile == $record['mobile2']) {
                        $RecordModel->where('flowId', $signFlowId)->update(['user2_sign_status' => 1]);
                    }


                    break;

                case 'SIGN_MISSON_COMPLETE':
                    //签署人签署完成回调
                    $signFlowId = $result['signFlowId'];
                    $signResult = $result['signResult'];
                    $accountMobile = $result['operator']['psnAccount']['accountMobile'];
                    $record = $RecordModel->where('flowId', $signFlowId)->find();
                    if (empty($record)) {
                        echo '信息异常';
                    }
                    if ($accountMobile == $record['mobile1']) {
                        $signResult == 2 && $RecordModel->where('flowId', $signFlowId)->update(['user1_sign_status' => 2,'user1_sign_time'=>time()]);
                    }
                    if ($accountMobile == $record['mobile2']) {
                        $signResult == 2 && $RecordModel->where('flowId', $signFlowId)->update(['user2_sign_status' => 2,'user2_sign_time'=>time()]);
                    }

                    if ($signResult != 2) {
                        $RecordModel->where('flowId', $signFlowId)->update(['status' => 5]);
                    }
                    break;

                case 'SIGN_FLOW_COMPLETE':
                    //流程结束逻辑处理
                    $signFlowId = $result['signFlowId'];
                    $signFlowStatus = $result['signFlowStatus'];
                    if ($signFlowStatus == 2) {
                        $RecordModel->where('flowId', $signFlowId)->update([
                            'status' => 2,
                            'user1_sign_status' => 2,
                            'user2_sign_status' => 2,
                        ]);
                    }
                    if ($signFlowStatus == 3) {
                        $RecordModel->where('flowId', $signFlowId)->update([
                            'status' => 3,
//                            'user1_sign_status'=>0,
//                            'user2_sign_status'=>0,
                        ]);
                    }

                    if ($signFlowStatus == 5) {
                        $RecordModel->where('flowId', $signFlowId)->update([
                            'status' => 5,
//                            'user1_sign_status'=>0,
//                            'user2_sign_status'=>0,
                        ]);
                    }

                    if ($signFlowStatus == 7) {
                        $RecordModel->where('flowId', $signFlowId)->update([
                            'status' => 5,
//                            'user1_sign_status'=>0,
//                            'user2_sign_status'=>0,
                        ]);
                    }

                    $record = $RecordModel->where('flowId', $signFlowId)->find();
                    if ($record['mobile1']&& $record['user1_sign_status']==2&& $record['mobile2']&&$record['user2_sign_status']==2){
                        $RecordModel->where('flowId', $signFlowId)->update([
                            'status' => 2,
                            'is_success' => 1,
//                            'user1_sign_status'=>0,
//                            'user2_sign_status'=>0,
                        ]);
                    }
                    break;

                case 'SIGN_FLOW_INITIATED':
                    //发起成功通知
                    break;
                case 'AUTH_PASS':
                    //查询用户信息
                    $uinfo = (new \app\admin\model\User())->where('authFlowId', $result['authFlowId'])->find();
                    if (empty($uinfo)) {
                        fwrite($file, "未找到用户：{$result['authFlowId']}\n");
                    }
                    (new \app\admin\model\User())->where('id', $uinfo['id'])->update(['is_auth' => 1, 'psnId' => $result['psnInfo']['psnId']]);
                    fwrite($file, "实名认证成功：{$uinfo['mobile']}\n");
                    break;

                    case 'AUTHORIZE_FINISH':
                    //查询用户信息
                    $uinfo = (new \app\admin\model\User())->where('authFlowId', $result['authFlowId'])->find();
                    if (empty($uinfo)) {
                        fwrite($file, "未找到用户：{$result['authFlowId']}\n");
                    }
                    (new \app\admin\model\User())->where('id', $uinfo['id'])->update(['is_auth' => 1, 'psnId' => $result['psnId']]);
                    fwrite($file, "授权成功：{$uinfo['mobile']}\n");
                    break;
            }
        } catch (\Exception $e) {
            fwrite($file, "回调失败" . $e->getMessage() . "\n");
        }
    }
}
